package com.framework.core.rest;

import com.framework.core.ValidateParam;
import com.framework.core.utils.SignUtil;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Set;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author shenmengchao
 * @version 1.0.0
 * @date 2017/8/11
 * @description
 */

public class SignInterceptor implements Interceptor {


    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        HttpUrl httpUrl = request.url();
        HashMap<String, Object> map = new HashMap<>();
        Set<String> nameSet = httpUrl.queryParameterNames();
        for (String s : nameSet) {
            String value = httpUrl.queryParameter(s);
            map.put(s, value);
        }
        String sign = "";
        String accessAction = (String) map.get("accessAction");
        String accessKey = getAccessKey(accessAction);
        String accessSecret = getAccessSecret(accessAction);
        try {
            map.put("accessKey", accessKey);
            sign = SignUtil.generateSignature(map, accessSecret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String newUrl = buildUrl(httpUrl.url(), accessKey, sign);
        Request newRequest = request.newBuilder().url(newUrl).build();
        return chain.proceed(newRequest);
    }

    private String getAccessKey(String accessAction) {
        if (accessAction.contains("getAccountsByStbId")) {
            return ValidateParam.ACCESS_KEY_STB;
        } else {
            return ValidateParam.ACCESS_KEY;
        }
    }

    private String getAccessSecret(String accessAction) {
        if (accessAction.contains("getAccountsByStbId")) {
            return ValidateParam.SECRET_STB;
        } else {
            return ValidateParam.SECRET;
        }
    }

    private String buildUrl(URL url, String accessKey, String signature) {
        String urlStr = url.toString();
        StringBuilder sb = new StringBuilder(urlStr);
        if (urlStr.contains("?")) {
            sb.append("&accessKey=");
            sb.append(accessKey);
            sb.append("&signature=");
            sb.append(signature);
        } else {
            sb.append("?accessKey=");
            sb.append(accessKey);
            sb.append("&signature=");
            sb.append(signature);
        }
        return sb.toString();
    }


}
